//
//  ClientLoginViewController.m
//  YYZB
//
//  Created by 顾悦 on 16/3/23.
//
//

#import "ClientLoginViewController.h"

#import "UserInfoController.h"

#import "UserWebService.h"

#import "VerifyCode.h"
#import "NSString+MD5.h"

#import "LoadingView.h"

#define TotalTimerCount 60

@interface ClientLoginViewController ()

@property (strong, nonatomic) UserWebService *userWebService;

@property (strong, nonatomic) VerifyCode *verifyCode;

@property (strong, nonatomic) NSTimer *timer;
@property (nonatomic) NSUInteger timerCount;

@end

@implementation ClientLoginViewController

#pragma mark -

- (UserWebService *)userWebService {
    if (!_userWebService) {
        _userWebService = UserWebService.new;
    }
    
    return _userWebService;
}

#pragma mark -

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if ([UserInfoController userNo].length) {
        self.usernameTextField.text = [UserInfoController userNo];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 

- (void)handleLoginResult:(NSArray *)items userNo:(NSString *)userNo error:(NSError *)error {
    [LoadingView dismiss];
    if (error) {
        [LoadingView showToast:[error localizedDescription]];
    } else {
        NSDictionary *item = items.lastObject;
        [UserInfoController setUserNo:userNo];
        [UserInfoController setUserID:item[@"UserId"]];
        [UserInfoController setSessionKey:item[@"SessionKey"]];
        // set session
        if (self.completionHandler) {
            self.completionHandler();
        }
    }
}

- (IBAction)submitButtonTapped:(id)sender {
    [LoadingView show];
    if ([self isUsingVerifyCode]) {
        [self.userWebService login:self.usernameTextField.text verifyCode:self.verifyCodeTextField.text verifyCodeID:self.verifyCode.ID ?: @"" completionHanlder:^(NSArray *items, NSError *error) {
            [self handleLoginResult:items userNo:self.usernameTextField.text error:error];
        }];
    } else {
        [self.userWebService login:self.usernameTextField.text password:/*[*/self.passwordTextField.text/* MD5]*/ completionHanlder:^(NSArray *items, NSError *error) {
            [self handleLoginResult:items userNo:self.usernameTextField.text error:error];
        }];
    }
}

- (IBAction)verifyCodeButtonTapped:(id)sender {
    [LoadingView show];
    [self.userWebService getVerifyCode:self.usernameTextField.text flag:@"0" completionHanlder:^(NSArray *items, NSError *error) {
        [LoadingView dismiss];
        if (error) {
            [LoadingView showToast:[error localizedDescription]];
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.verifyCode = [[VerifyCode alloc] initWithDictionary:items.firstObject];
                self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerTicked:) userInfo:nil repeats:YES];
                self.timerCount = TotalTimerCount;
            });
        }
    }];
}

#pragma mark -

- (void)timerTicked:(NSTimer *)timer {
    dispatch_async(dispatch_get_main_queue(), ^{
        self.timerCount -= 1;
        if (self.timerCount == 0) {
            self.timerCount = TotalTimerCount;
            self.verifyCodeButton.enabled = YES;
            self.verifyCodeButton.title = @"获取验证码";
            [self.timer invalidate];
            self.timer = nil;
        } else {
            self.verifyCodeButton.title = [NSString stringWithFormat:@"%@秒", @(self.timerCount)];
            self.verifyCodeButton.enabled = NO;
        }
    });
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
